const websocket = require('socket.io')
const UserLogin = require('../model/UserLogin')
const Koa = require('koa')
const app = new Koa().callback()
var http = require('http').createServer(app)
var socketIO = require('socket.io')(http, { transports: ['websocket'] })
var axios = require('axios')
const localKey = 'hmlgnb' // 用于记录本地服务的特殊标记
const socketPool = {} // socket对象池
let socketObj = null
socketIO.on('connection', async function(socket){
    socketObj = socket
    console.log("黑马头条-小智同学通讯开始连接!")
    var token = socket.request._query.token // 获取用户id
    if (socket.request._query.key === localKey) {
        // 特殊标记
        socketPool[localKey] = socketPool[localKey] || []
        socketPool[localKey].push(socket.id) 
    }else {
        if(token) {
            const lgPeople = await UserLogin.findOne({ token }).lean()
            if (lgPeople) {
             socketPool[lgPeople.user_id] = socket.id
             console.log("验证通过token验证") 
            }else {
             console.log("没有找到对应的登录记录, 主动断开连接") 
             // socket.emit('disconnect')
            }
         }else {
             console.log("黑马头条-小智同学验证token没有传递, 主动断开连接")
             // socket.emit('disconnect')
         }
    }
    socket.on('message',async function(obj){
        console.log("有人对小智说:" + obj.msg)
        try {
            const { data: { content } } = await axios({
                url: 'http://api.qingyunke.com/api.php',
                params: { key: 'free', appid: 0, msg: obj.msg }
            })
             socket.emit('message', { msg: content, timestamp: new Date().getTime() })
        } catch (error) {
            socket.emit('message', { msg: '你把小智整不会了,你真有点小可爱哦', timestamp: new Date().getTime() })
        }
    });
    socket.on('send',async function(msg){
        console.log("有人对小智说:" + msg)
        try {
            const { data: { content } } = await axios({
                url: 'http://api.qingyunke.com/api.php',
                params: { key: 'free', appid: 0, msg }
            })
             socket.emit('message', content)
        } catch (error) {
            socket.emit('message', '你把小智整不会了,你真有点小可爱哦')
        }
    });
    socket.on('disconnect', function(){
        console.log("黑马头条-小智同学通讯断开!")
        delete socketPool[socket.id] // 释放缓存
    });

  });
  // 获取socket对象
  module.exports =  {
    // 给某人发消息
    sendMessageByUserId (user_id, type, message) {
        if(!socketPool[user_id]) {
            console.log("该socket消息已断开连接!")
            return
        }
        socketObj.broadcast.to(socketPool[user_id]).emit(type, message) // 给指定的某人发消息
    },
    // 群发消息
   sendAllMessage (type, message) {
     socketIO.emit(type, message)
   },
   // 发送本地服务消息
   sendLocalMessage (type, message) {
     if (socketPool[localKey] &&  socketPool[localKey].length) {
         const localList =  socketPool[localKey]
         localList.forEach(id => {
            const obj = socketIO.sockets.sockets.get(id)
            if (obj) {
                obj.emit(type, message)// 给指定的某人发消息
            }
         });
     }else {
        console.log("无法连接本地服务")
     }
   }
  }
  http.listen(8001, function () {
      console.log("小智同学通讯服务启动! 地址: http://localhost:8001")
  })